<template>
    <!-- 授权用户 -->
    <el-dialog :close-on-click-modal="false" v-model="visible" append-to-body title="选择用户" top="5vh" width="60%">
        <el-form ref="queryParamsRef" :inline="true" :model="queryParams"  >
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model="queryParams.userName" clearable placeholder="请输入用户名称"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="queryParams.phonenumber" clearable placeholder="请输入手机号码"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <div style="float: right" class="mr20">
                <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
            </div>
        </el-form>
        <el-row class="div-height-left">
            <el-col :span="5" class="div-height-left">
                <!--科室树-->
                <dept-tree class="dept-tree-height" ref="deptTree" :org-id="queryParams.orgId" @treeClick="treeClick" />
            </el-col>
            <el-col :span="19" :xs="24">
                <el-row>
                    <el-table ref="table" height="300px" :data="userList" :border="true" stripe highlight-current-row :header-cell-style="$headerCellStyle"
                        @select="onTableSelect" @selection-change="handleSelectionChange" @select-all="selectAll">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column :show-overflow-tooltip="true" label="所属机构" prop="orgName" />
                        <el-table-column :show-overflow-tooltip="true" label="所属科室" prop="dept.deptName" />
                        <el-table-column :show-overflow-tooltip="true" label="用户名称" prop="userName" />
                        <el-table-column :show-overflow-tooltip="true" label="用户昵称" prop="nickName" />
                        <el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email" />
                        <el-table-column :show-overflow-tooltip="true" label="手机" prop="phonenumber" />
                        <el-table-column :align="'center'" label="状态" prop="status">
                            <template #default="scope">
                                <dict-data-tag :options="dictDataMap['sys_normal_disable']" :value="scope.row.status" />
                            </template>
                        </el-table-column>
                        <el-table-column :align="'center'" label="创建时间" prop="createTime" width="180">
                            <template #default="scope">
                                <span>{{ $parseTime(scope.row.createTime) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination style="margin-left: 14px;" v-show="total > 0" v-model:limit="queryParams.pageSize"
                        v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
                </el-row>
                <el-row style="margin-top: 40px">
                    <el-col :span="12">
                        <el-card class="box-card">
                            <div style="height: 240px;">
                                <span>已授权人员：{{ haveBeenAuthorized.length }}人</span>
                                <div class="div-tag">
                                    <el-tag v-for="tag in haveBeenAuthorized" :key="tag.name" :type="tag.type"
                                        class="tag-margin">
                                        {{ tag.name }}
                                    </el-tag>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="box-card">
                            <div style="height: 240px;">
                                <span>已选人员：</span>
                                <el-button :disabled="tags.length === 0" type="danger" @click="emptyTags">
                                    清空
                                </el-button>
                                <div class="div-tag">
                                    <el-tag v-for="tag in tags" :key="tag.name" :type="tag.type" class="tag-margin" closable
                                        @close="handleClose(tag)">
                                        {{ tag.name }}
                                    </el-tag>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
        <template #footer>
            <span class="dialog-footer">
                <el-button   type="primary" @click="handleSelectUser">保 存</el-button>
                <el-button   @click="visible = false">取 消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import {
    allocated,
    authUserSelectAll,
    deptGroupAllocated,
    deptGroupAuthUserSelectAll,
    deptGroupUnallocatedUserList,
    unallocatedUserList
} from "@/api/system/role";
import { useUserStoreHook } from "@/store/modules/user";
import { useDictStoreHook } from "@/store/modules/dict";
const table = ref()
const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook()
const dictDataMap = ref(dictStore.isTypeGetData('sys_normal_disable'))
const emits = defineEmits(["ok"])
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 遮罩层
const visible = ref(false)
// 选中数组值
const userIds = ref([])
// 总条数
const total = ref(0)
// 未授权用户数据
const userList = ref([])
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    roleId: undefined,
    userName: undefined,
    phonenumber: undefined,
    deptGroupId: undefined,
    businessType: ''
})
// 已添加人员
const tags = ref<any[]>([])
// 已授权人员
const haveBeenAuthorized = ref<any[]>([])
// 已勾选列表数据
const selection = ref([])

/** 删除已选择人员 */
function handleClose(tag: any) {
    nextTick(() => {
        table.value.toggleRowSelection(selection.value.filter((item: any) => {
            return item.userId === tag.userId;
        }), false)
    })
    // @ts-ignore
    tags.value.splice(tags.value.indexOf(tag), 1)
    getList()
}
function onTableSelect(rows, row) {
    let selected = rows.length && rows.indexOf(row) !== -1
    if (!selected) {
        let exclusionOfExistence = tags.value.filter((item: any) => {
            return item.userId !== row.userId;
        });
        tags.value = exclusionOfExistence
    }
}

// 多选框选中数据
function handleSelectionChange(selection) {
    selection.value = selection
    resArr(selection, tags.value)
}
function selectAll(selection) {
    if (selection.length === 0) {
        return tags.value = []
    }
    resArr(selection, tags.value)
}
/** 清空待选 */
function emptyTags() {
    tags.value = []
    table.value.clearSelection()
}
function resArr(arr1, arr2) {
    let resArr = arr1.filter((v) => arr2.every((val) => val.userId !== v.userId))
    return resArr.forEach(item => {
        let tag: any = {
            name: item.dept.deptName + ' | ' + item.nickName,
            userId: item.userId,
            type: 'warning',
            isNew: true
        }
        // @ts-ignore
        tags.value.push(tag)
    })
}

// 显示弹框
function show(parentQueryParams) {
    haveBeenAuthorized.value = []
    queryParams.value.businessType = parentQueryParams.businessType;
    queryParams.value.roleId = parentQueryParams.roleId;
    queryParams.value.deptGroupId = parentQueryParams.deptGroupId;
    queryParams.value.orgId = userInfo.orgId || parentQueryParams.orgId
    getList();
    if (queryParams.value.businessType === '1') {
        allocated(queryParams.value).then(res => {
            let data = res.data
            data.forEach(item => {
                let tag: any = {
                    name: item.dept.deptName + '|' + item.nickName,
                    userId: item.userId,
                    type: 'success',
                    isNew: false
                }
                // @ts-ignore
                haveBeenAuthorized.value.push(tag)
            })
        })
    } else if (queryParams.value.businessType === '2') {
        deptGroupAllocated(queryParams.value).then(res => {
            let data = res.data
            data.forEach(item => {
                let tag = {
                    name: item.dept.deptName + ' | ' + item.nickName,
                    userId: item.userId,
                    type: 'success',
                    isNew: false
                }
                // @ts-ignore
                haveBeenAuthorized.value.push(tag)
            })
        })
    }

    visible.value = true;
}
// 查询表数据
function getList() {
    if (queryParams.value.businessType === '1') {
        unallocatedUserList(queryParams.value).then((res: any) => {
            userList.value = res.rows;
            total.value = res.total;
            // 列表默认选中
            nextTick(() => {
                userList.value.forEach((row: any) => {
                    tags.value.forEach((selected: any) => {
                        if (selected.userId === row.userId) {
                            table.value.toggleRowSelection(row, true);
                        }
                    })
                })
            })
        });
    } else if (queryParams.value.businessType === '2') {
        deptGroupUnallocatedUserList(queryParams.value).then((res: any) => {
            userList.value = res.rows;
            total.value = res.total;
            // 列表默认选中
            nextTick(() => {
                userList.value.forEach((row: any) => {
                    tags.value.forEach((selected: any) => {
                        if (selected.userId === row.userId) {
                            table.value.toggleRowSelection(row, true);
                        }
                    })
                })
            })
        });
    }

}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.deptId = ''
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    handleQuery();
}
/** 选择授权用户操作 */
function handleSelectUser() {
    //@ts-ignore
    userIds.value = tags.value.map((item: any) => item.userId);
    const userIdsThis = userIds.value.join(",");
    if (userIdsThis === "") {
        return ElMessage.success("请选择要分配的用户");
    }
    if (queryParams.value.businessType === '1') {
        const roleId = queryParams.value.roleId;
        let param = { roleId: roleId, list: tags.value }
        authUserSelectAll(param).then((res: any) => {
            ElMessage.success(res.msg);
            if (res.code === 200) {
                visible.value = false;
                emptyTags()
                emits("ok");
            }
        });
    } else if (queryParams.value.businessType === '2') {
        const deptGroupId = queryParams.value.deptGroupId;
        let param = { deptGroupId: deptGroupId, list: tags.value }
        deptGroupAuthUserSelectAll(param).then((res: any) => {
            ElMessage.success(res.msg);
            if (res.code === 200) {
                visible.value = false;
                emptyTags()
                emits("ok");
            }
        });
    }

}
/** 左侧科室树节点点击事件 */
function treeClick(obj) {
    queryParams.value.deptId = obj.id
    getList()
}

defineExpose({
    show
})
</script>

<style lang="scss" scoped>
:deep(.el-dialog__footer) {
    padding-top: 30px;
}

.box-card {
    margin: 10px 10px 10px 10px;
    height: 280px;
}

.tag-margin {
    margin: 10px 10px 0px 10px
}

.div-tag {
    margin: 10px 5px 5px 10px;
    height: 100%;
    overflow-y: auto
}
</style>
